<template>
  <a-modal
    v-model:open="dialogVisible"
    :title="isEdit ? '编辑转换规则' : '新建转换规则'"
    :width="600"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :confirm-loading="submitting"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
    >
      <a-form-item label="转换名称" name="name">
        <a-input
          v-model:value="formData.name"
          placeholder="请输入转换名称"
        />
      </a-form-item>

      <a-form-item label="转换描述" name="description">
        <a-textarea
          v-model:value="formData.description"
          placeholder="请输入转换描述"
          :rows="3"
        />
      </a-form-item>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="源状态" name="from_state_id">
            <a-select
              v-model:value="formData.from_state_id"
              placeholder="选择源状态"
              :disabled="isEdit"
            >
              <a-select-option
                v-for="state in availableFromStates"
                :key="state.id"
                :value="state.id"
              >
                <div class="state-option">
                  <StateTag :state="state" variant="outlined" />
                </div>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="目标状态" name="to_state_id">
            <a-select
              v-model:value="formData.to_state_id"
              placeholder="选择目标状态"
              :disabled="isEdit"
            >
              <a-select-option
                v-for="state in availableToStates"
                :key="state.id"
                :value="state.id"
              >
                <div class="state-option">
                  <StateTag :state="state" variant="outlined" />
                </div>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="转换预览" v-if="formData.from_state_id && formData.to_state_id">
        <div class="transition-preview" v-if="getStateById(formData.from_state_id) && getStateById(formData.to_state_id)">
          <StateTag :state="getStateById(formData.from_state_id)!" variant="outlined" />
          <Icon name="arrow-right" class="arrow" />
          <StateTag :state="getStateById(formData.to_state_id)!" variant="outlined" />
        </div>
      </a-form-item>

      <a-form-item label="状态属性">
        <a-checkbox v-model:checked="formData.is_enabled">
          启用转换
        </a-checkbox>
      </a-form-item>

      <a-form-item label="转换条件" name="conditions">
        <a-textarea
          v-model:value="conditionsText"
          placeholder="请输入转换条件（JSON格式）"
          :rows="4"
        />
        <div class="form-help">
          转换条件用于控制何时允许执行此转换，格式为JSON对象
        </div>
      </a-form-item>

      <a-form-item label="转换动作" name="actions">
        <a-textarea
          v-model:value="actionsText"
          placeholder="请输入转换动作（JSON格式）"
          :rows="4"
        />
        <div class="form-help">
          转换动作用于定义执行转换时的附加操作，格式为JSON对象
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { message, type FormInstance } from 'ant-design-vue'
import type { StateResponse } from '@/types/state'
import type { StateTransition, StateTransitionCreate, StateTransitionUpdate } from '@/api/state'
import { stateTransitionApi } from '@/api/state'
import StateTag from './StateTag.vue'
import Icon from '@/components/ui/Icon.vue'

interface Props {
  open: boolean
  transition?: StateTransition | null
  states: StateResponse[]
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:open': [value: boolean]
  success: []
}>()

// 使用状态管理store
// const stateStore = useStateStore()

const formRef = ref<FormInstance>()
const submitting = ref(false)

const dialogVisible = computed({
  get: () => props.open,
  set: (value) => emit('update:open', value)
})

const isEdit = computed(() => !!props.transition)

const formData = ref<StateTransitionCreate & { id?: string }>({
  from_state_id: '',
  to_state_id: '',
  name: '',
  description: '',
  is_enabled: true,
  conditions: {},
  actions: {}
})

const conditionsText = ref('')
const actionsText = ref('')

// 可选择的源状态（排除最终状态）
const availableFromStates = computed(() => {
  if (!props.states || !Array.isArray(props.states)) {
    return []
  }
  return props.states.filter(state => state.is_enabled)
})

// 可选择的目标状态（排除当前选择的源状态）
const availableToStates = computed(() => {
  if (!props.states || !Array.isArray(props.states)) {
    return []
  }
  return props.states.filter(state => 
    state.is_enabled && state.id !== formData.value.from_state_id
  )
})

const formRules = {
  name: [
    { required: true, message: '请输入转换名称', trigger: 'blur' },
    { min: 1, max: 100, message: '转换名称长度为1-100个字符', trigger: 'blur' }
  ],
  from_state_id: [
    { required: true, message: '请选择源状态', trigger: 'change' }
  ],
  to_state_id: [
    { required: true, message: '请选择目标状态', trigger: 'change' }
  ]
}

// 根据ID获取状态
const getStateById = (stateId: string) => {
  return props.states.find(state => state.id === stateId)
}

// 重置表单
const resetForm = () => {
  formData.value = {
    from_state_id: '',
    to_state_id: '',
    name: '',
    description: '',
    is_enabled: true,
    conditions: {},
    actions: {}
  }
  conditionsText.value = ''
  actionsText.value = ''
}

// 填充表单数据
const fillFormData = (transition: StateTransition) => {
  formData.value = {
    id: transition.id,
    from_state_id: transition.from_state_id,
    to_state_id: transition.to_state_id,
    name: transition.name,
    description: transition.description || '',
    is_enabled: transition.is_enabled,
    conditions: transition.conditions || {},
    actions: transition.actions || {}
  }
  
  conditionsText.value = transition.conditions 
    ? JSON.stringify(transition.conditions, null, 2) 
    : ''
  actionsText.value = transition.actions 
    ? JSON.stringify(transition.actions, null, 2) 
    : ''
}

// 解析JSON文本
const parseJsonText = (text: string) => {
  if (!text.trim()) return {}
  try {
    return JSON.parse(text)
  } catch (error) {
    throw new Error('JSON格式错误')
  }
}

// 处理提交
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    
    // 验证JSON格式
    try {
      formData.value.conditions = parseJsonText(conditionsText.value)
      formData.value.actions = parseJsonText(actionsText.value)
    } catch (error) {
      message.error('JSON格式错误，请检查条件和动作的格式')
      return
    }
    
    // 验证转换规则
    if (formData.value.from_state_id === formData.value.to_state_id) {
      message.error('源状态和目标状态不能相同')
      return
    }
    
    submitting.value = true
    
    if (isEdit.value && props.transition) {
      // 编辑转换
      const updateData: StateTransitionUpdate = {
        name: formData.value.name,
        description: formData.value.description,
        is_enabled: formData.value.is_enabled,
        conditions: formData.value.conditions,
        actions: formData.value.actions
      }
      
      await stateTransitionApi.updateTransition(props.transition.id, updateData)
      message.success('转换规则更新成功')
    } else {
      // 创建转换
      const createData: StateTransitionCreate = {
        from_state_id: formData.value.from_state_id,
        to_state_id: formData.value.to_state_id,
        name: formData.value.name,
        description: formData.value.description,
        is_enabled: formData.value.is_enabled,
        conditions: formData.value.conditions,
        actions: formData.value.actions
      }
      
      await stateTransitionApi.createTransition(createData)
      message.success('转换规则创建成功')
    }
    
    emit('success')
    dialogVisible.value = false
  } catch (error: any) {
    console.error('提交失败:', error)
    
    // 更详细的错误处理
    let errorMessage = isEdit.value ? '转换规则更新失败' : '转换规则创建失败'
    
    if (error?.response?.data?.detail) {
      errorMessage = error.response.data.detail
    } else if (error?.message) {
      errorMessage = error.message
    }
    
    message.error(errorMessage)
  } finally {
    submitting.value = false
  }
}

// 处理取消
const handleCancel = () => {
  dialogVisible.value = false
}

// 监听对话框显示状态
watch(
  () => props.open,
  (open) => {
    if (open) {
      if (props.transition) {
        fillFormData(props.transition)
      } else {
        resetForm()
      }
    } else {
      formRef.value?.resetFields()
    }
  }
)

// 监听目标状态变化，清空目标状态选择
watch(
  () => formData.value.from_state_id,
  () => {
    if (formData.value.to_state_id === formData.value.from_state_id) {
      formData.value.to_state_id = ''
    }
  }
)
</script>

<style scoped>
.state-option {
  display: flex;
  align-items: center;
}

.transition-preview {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #fafafa;
  border-radius: 6px;
}

.arrow {
  color: #8c8c8c;
  font-size: 16px;
}

.form-help {
  font-size: 12px;
  color: #8c8c8c;
  margin-top: 4px;
}
</style>